package com.koicarp.university.graduate.web.controller.wxapp;

import com.alibaba.fastjson.JSONReader;
import com.koicarp.university.graduate.service.entity.Collect;
import com.koicarp.university.graduate.service.entity.LoginSessionWx;
import com.koicarp.university.graduate.service.entity.graduateInfoManage.GraduateInfo;
import com.koicarp.university.graduate.service.service.graduateInfoManage.IGraduateInfoService;
import com.koicarp.university.graduate.service.service.information.ICollectService;
import com.koicarp.university.graduate.service.service.information.IInformationService;
import com.koicarp.university.graduate.service.service.report.IReportService;
import com.koicarp.university.graduate.service.service.report.ISchoolReportService;
import com.koicarp.university.graduate.service.service.wx.ILoginSessionWxService;
import com.koicarp.university.graduate.service.vo.graduateInfoManage.InfoStatusVo;
import com.koicarp.university.graduate.service.vo.information.InformationVo;
import com.koicarp.university.graduate.service.vo.wx.*;
import com.koicarp.university.graudate.common.constant.BaseConstant;
import com.koicarp.university.graudate.common.utils.HttpUtils;
import com.koicarp.university.graudate.common.utils.UniversityResponse;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.StringReader;
import java.util.*;

/**
 * @auther liutao
 * @Date 2020-10-24 10:54:43
 */
@Slf4j
@RestController
@RequestMapping("wx/loginSession")
@RequiredArgsConstructor
public class LoginSessionController {
    //    小程序AppId,AppSecret
    private static String APPID="wxfd1639816c6b7972";
    private static String SECRET="fae93f04965f184ee945562b79417b5b";

    private final IReportService reportService;
    private final ISchoolReportService schoolReportService;

    private final HttpUtils httpUtils;

    private final ILoginSessionWxService loginSessionWxService;

    private final IInformationService informationService;

    private final IGraduateInfoService graduateInfoService;

    private final ICollectService collectService;
    /**
     * 登录并获取token
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("getToken")
    public UniversityResponse getToken( LoginSessionVo loginSessionVo){
        String url=" https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+SECRET+"&js_code="+loginSessionVo.getCode()+"&grant_type=authorization_code";
        log.info("code:                    "+loginSessionVo.getCode());
        Map<String,String> map=new HashMap<String, String>();
        String jsonString=httpUtils.doGet(url,map);
        jsonString="["+jsonString+"]";
        List<Map<String, String>> list= jsonToList(jsonString);
        String token = "token_" + new Date().getTime();
        return loginSessionWxService.login(list.get(0).get("openid"),token);

    }

    @ResponseBody
    @RequestMapping("checkToken")
    public UniversityResponse checkToken(String token){
        UniversityResponse response=null;
        try{
            response = loginSessionWxService.checkToken(token);
        }catch (Exception e){
            log.error("验证失败",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }
    /**
     * 将json字符串转换成list
     * @param json
     * @return
     */
    public static List<Map<String, String>> jsonToList(String json) {
        JSONReader reader = new JSONReader(new StringReader(json));// 已流的方式处理，这里很快
        reader.startArray();
        List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
        Map<String, String> map = null;
        int i = 0;
        while (reader.hasNext()) {
            i++;
            reader.startObject();// 这边反序列化也是极速
            map = new HashMap<String, String>();
            while (reader.hasNext()) {
                String arrayListItemKey = reader.readString();
                String arrayListItemValue = reader.readObject().toString();
                map.put(arrayListItemKey, arrayListItemValue);
            }
            rsList.add(map);
            reader.endObject();
        }
        reader.endArray();
        return rsList;
    }


    @PostMapping("getInformationWithPage")
    @ApiOperation(value = "资讯查询-普通查询，分页",notes = "资讯查询-普通查询，分页")
    public UniversityResponse getInformationWithPage(@RequestBody InformationVo vo){
        UniversityResponse response=null;
        try{
            if (vo.getSort().equals("+id")){
                vo.setSort("asc");
            }else{
                vo.setSort("desc");
            }
            response = informationService.getInformationWithPage(vo);
        }catch (Exception e){
            log.error("查询失败",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }


    @PostMapping("authIdentity")
    public UniversityResponse authIdentity(@RequestBody AuthIdentityVo vo){
        UniversityResponse response=null;
        try{

            response = graduateInfoService.authIdentity(vo);
        }catch (Exception e){
            log.error("认证失败",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }
    @PostMapping("getOneById")
    public UniversityResponse getOneById(@RequestBody GraduateInfo graduateInfo){
        UniversityResponse response=null;
        try{

            response = graduateInfoService.getOneById(graduateInfo.getId());
        }catch (Exception e){
            log.error("认证失败",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    @PostMapping("updateGraduateWx")
    public UniversityResponse updateGraduateWx(@RequestBody InfoStatusVo infoStatusVo){
        UniversityResponse response=null;
        try{

            response = graduateInfoService.updateGraduate(infoStatusVo);
        }catch (Exception e){
            log.error("认证失败",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    @PostMapping("saveReportInfo")
    @ApiOperation(value = "wx-保存学生相关报表填写数据")
    public UniversityResponse saveReportInfo(@RequestBody ReportVo reportVo){
        UniversityResponse response=null;
        try{
            response = reportService.saveReportInfo(reportVo);
        }catch (Exception e){
            log.error("查询",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    @PostMapping("saveReportSchoolInfo")
    @ApiOperation(value = "wx-保存学校相关报表填写数据")
    public UniversityResponse saveReportSchoolInfo(@RequestBody ReportSchoolVo reportSchoolVo){
        UniversityResponse response=null;
        try{
            response = schoolReportService.saveReportSchoolInfo(reportSchoolVo);
        }catch (Exception e){
            log.error("查询",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }
    @PostMapping("getCollectInfoWithPage")
    @ApiOperation(value = "wx-查询收藏的资讯")
    public UniversityResponse getCollectInfoWithPage(@RequestBody CollectInfoVo vo){
        UniversityResponse response=null;
        try{
            if (vo.getSort().equals("+id")){
                vo.setSort("asc");
            }else{
                vo.setSort("desc");
            }
            response = collectService.getCollectInfoWithPage(vo);
        }catch (Exception e){
            log.error("查询",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }
    @PostMapping("saveCollectInfo")
    @ApiOperation(value = "wx-保存收藏记录")
    public UniversityResponse saveCollectInfo(@RequestBody Collect collect){
        UniversityResponse response=null;
        try{
            response = collectService.insert(collect);
        }catch (Exception e){
            log.error("保存",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }
    @PostMapping("removeCollectInfo")
    @ApiOperation(value = "wx-删除收藏")
    public UniversityResponse removeCollectInfo(@RequestBody Collect collect){
        UniversityResponse response=null;
        try{
            response = collectService.deleteByGraIdWithInfoId(collect);
        }catch (Exception e){
            log.error("删除",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    @PostMapping("getCollectInfoByGraAndInfo")
    @ApiOperation(value = "wx-是否收藏")
    public UniversityResponse getCollectInfoByGraAndInfo(@RequestBody Collect collect){
        UniversityResponse response=null;
        try{
            response = collectService.getCollectInfoByGraAndInfo(collect);
        }catch (Exception e){
            log.error("查找",e);
            response = new UniversityResponse();
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

}
